﻿using System;
using Microsoft.JScript;
﻿using System.Reflection;
using System.CodeDom.Compiler;
using System.Collections.Generic;

namespace com.sharepointutils.application.Javascript
{
    public class JavascriptEngine
    {
        public Closure Function { get; set; }

        Microsoft.JScript.Vsa.VsaEngine engine = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();

        public void CompileFunction (String function)
        {
            object result = Microsoft.JScript.Eval.JScriptEvaluate("(" + function + ")", engine);
            this.Function = result as Closure;
        }

        public JSObject RunFunction(params object[] parameters)
        {
            JSObject result = null;
            if (this.Function != null)
            {
                result = this.Function.Invoke(this.Function, parameters) as JSObject;
            }
            return result;
        }

        public string Run(String function, params object[] parameters)
        {
            object result = Microsoft.JScript.Eval.JScriptEvaluate("(" + function + ")", engine);
            Closure close = result as Closure;
            result = close.Invoke(close, parameters);

            JSObject obj = result as JSObject;
            String[] value = JSArrayToStringArray(obj);
            return result.ToString();
        }

        public String[] JSArrayToStringArray(JSObject obj)
        {
            List<String> array = new List<string>();
            foreach (String s in obj)
            {
                array.Add(obj[s].ToString());
            }
            return array.ToArray();
        }

        public object evalutate(String obj)
        {
            object result = Microsoft.JScript.Eval.JScriptEvaluate(obj, engine);
            return result;
        }

        public object toJSVariable(String[] variable)
        {
            String value = "[";
            int count = 1;
            foreach (String s in variable)
            {
                value += "'" + s + "'";
                if (variable.Length > 1 && count < variable.Length)
                {
                    value += ",";
                }
                count++;
            }
            value += "]";
            return evalutate(value);
        }

    }
}
